//
//  ContactChatListViewController+TextViewDelegate.m
//  DoctorYL
//
//  Created by Lisa on 16/8/3.
//  Copyright © 2016年 yuntai. All rights reserved.
//

#import "ContactChatListViewController+TextViewDelegate.h"
#import "ChartMessage.h"
#import "IWxChatMgrChat.h"
#import "CameraTakeMamanger.h"
#import "AudioTransition.h"
#import "AudioManager.h"
#import "ChartCellFrame.h"
#import "IWxChatMgrGroup.h"
//#import "LAnyChatManager.h"
//#import "ChatMemberEntity.h"
#import "ChatGroupMember.h"
//#import "ContactSelectMutVideoViewController.h"
#import "NSString+Path.h"
#import "SaveImageUtils.h"
//#import "ContactCollectChatListViewController.h"
#import "AuthorityManager.h"
#import "NSString+Verify.h"

#define kRecordAudioFile @"myRecord.caf"

@implementation ContactChatListViewController (TextViewDelegate)


#pragma mark - Public methods
// 添加输入框
- (void)addTextView
{
    CGFloat textHeight = 300;
    if (IS_IPHONE6P) {
        textHeight = 355;
    }
    NSLog(@"%f",kScreenBoundHeight);
    self.textView = [[ChatTextView alloc] initWithFrame:\
                     CGRectMake(0, kScreenBoundHeight -44 ,\
                                kScreenBoundWidth, textHeight)];
    self.textView.delegate = self;
    
    [self.view addSubview:self.textView];
    
    [self.textView addObserver:self forKeyPath:@"y"
                       options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
                       context:nil];


}


#pragma mark - CTAssetsPickerControllerDelegate, UINavigationControllerDelegate

// 选择完多张图片后的代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    if (assets.count == 0) return;
    // 取出图片
//    self.uploadCount = 0;
    for (int i = 0; i < assets.count; i++) {
        ALAsset *asset = assets[i];
        ALAssetRepresentation*rep = [asset defaultRepresentation];
        UIImage *img = [UIImage imageWithCGImage:rep.fullScreenImage];
        NSString *imageName = [NSString stringWithFormat:@"%@%d.png",[NSUUID UUID].UUIDString, i];
        NSString *imgPath = [SaveImageUtils saveChatImage:img withName:imageName];
        [self uploadChatImagePath:imgPath andImage:img];
        
    }
}

- (void)assetsPickerControllerDidCancel:(CTAssetsPickerController *)picker {
    
}

#pragma mark - AVAudioRecorderDelegate--录音成功
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSString *lastStr = [NSString stringFromNSDate:[NSDate date]];
    NSString *mp3Path = [self getMP3SavePathStrWithStr:lastStr];
    // 转换成MP3格式
    if ([[AudioTransition sharedInstance] MP3withCafPath:[self getSavePathStr] mp3Path:mp3Path] == NO) {
        WXLog(@" -----转码失败!");
        return;
    } else {
        if ([[NSFileManager defaultManager] removeItemAtPath:[self getSavePathStr]  error:nil]) {
            WXLog(@"录音原文件删除成功");
        }
    }
    // 如果录音太短不发送
    CGFloat duration = [AudioManager audioDurationWithPath:mp3Path];
    if (duration < 1.0) {
        WXLog(@"录音时间太短");
        if ([[NSFileManager defaultManager] removeItemAtPath:mp3Path error:nil]) {
            WXLog(@"录音删除成功");
        }
        return;
    }
    //语音路径转移，在录制期间转移 会导致转码失败 原因尚未可知
    NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Voice];
    [NSString checkFileFolderPathExist:localFilePathName];
    localFilePathName = [localFilePathName stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",lastStr]];
    NSError *error;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDone = [fileManager moveItemAtPath:mp3Path toPath:localFilePathName error:&error];
    WXLog(@"isDone = %d error = %@",isDone,error);
    //发送音频文件消息
    NSString *audioMessageId = nil;
    
    if (self.isToRoomChat) {//self.groupID
    }
    else
    {
        audioMessageId = [[IWxChatMgrChat sharedInstance] sendMessageVoiceToContact:self.contactMemID
                                                                       voiceFileURL:localFilePathName
                                                                           duration:duration
                                                                               desc:@"语音"
                                                                        isGroupChat:self.isToRoomChat
                                                                           progress:nil];
    }
    [self sendIMMessageContent:@"语音"
                     messageID:audioMessageId
              messaegeFilePath:localFilePathName
        messageFileServicePath:nil
               messageFileSize:0
                   messageType:kMessageAudio
                        durion:duration];
}

#pragma mark - ChatTextViewDelegate

// 即将输入
- (void)chatTextViewShouldEditing:(ChatTextView *)chatTextView
{
    
}

// 点击了发送按钮
- (void)chatTextView:(ChatTextView *)chatTextView sendMessage:(NSString *)text
{
    [self textMessage:text];
}
// 按下开始录音
- (void)chatTextViewBeginRecord:(ChatTextView *)chatTextView
{

    [[VoicePlayManager shareInstance]stopVoicePlay];
    if (![self.audioRecorder isRecording]) {
        self.audioRecorder.delegate = self;
        [self.audioRecorder record];
    }
}

// 松开结束录音
- (void)chatTextViewEndRecord:(ChatTextView *)chatTextView
{
    [self.audioRecorder stop];
}
//取消录音
- (void)chatTextViewCancleEndRecord:(ChatTextView *)chatTextView
{
    self.audioRecorder.delegate = nil;
    [self.audioRecorder stop];
    [self.audioRecorder deleteRecording];
}

/**
 *  打开 相册或拍照
 *
 *  @param tag          0 是照片或相机  1 是文件
 */
- (void)chatTextView:(ChatTextView *)chatTextView openCameraOrAlbumTag:(NSInteger)tag
{
    
    if (tag == 0) {
        if([[AuthorityManager sharedInstance]judgePhotoStatus]){
            [self selectPhotoAlbum];
        }
    }
    if (tag == 1){
        if ([[AuthorityManager sharedInstance]judgeCaramerStatus]) {
            [self selectCamare];
        }
    }
}
#pragma mark Event response
/**
 *  选择相册
 */
- (void)selectPhotoAlbum
{
    CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
    picker.maximumNumberOfSelection = 1;
    picker.delegate = self;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    [self presentViewController:picker animated:YES completion:NULL];
}
/**
 *  选择相机
 */
- (void)selectCamare
{
    [[CameraTakeMamanger sharedInstance] imageWithCameraInController:self handler:^(UIImage *image, NSString *imagePath) {
        [self uploadChatImagePath:imagePath andImage:image];
    } cancelHandler:^{
        
    }isIM:YES];
}
#pragma mark - Private methds
- (void)textMessage:(NSString *)message
{
    ;
    //获取的消息文本再次发起网络请求
    if (message.length <= 0)
    {
        [HUDManager showWarningWithText:@"消息为空!"];
        return;
    }
    if ([NSString IsEmptySpace:message] == NO) {
        [HUDManager showWarningWithText:@"消息为空!"];
        return;
    }

    //消息内容
    //生成消息对象
    NSString *messageId = nil;
    messageId = [[IWxChatMgrChat sharedInstance] sendMessageText:message
                                                           toContact:self.contactMemID
                                                         isGroupChat:NO
                                                            delegate:self];
    
    [self sendIMMessageContent:message
                     messageID:messageId
              messaegeFilePath:@""
        messageFileServicePath:@""
               messageFileSize:0
                   messageType:kMessageText
                        durion:0];
}
/**
 *  上传图片
 *
 *   imagePath
 *   image     
 */
- (void)uploadChatImagePath:(NSString *)imagePath andImage:(UIImage *)image
{

    
    NSFileManager* manager = [NSFileManager defaultManager];
    NSInteger fileSize = 0;
    if ([manager fileExistsAtPath:imagePath]){
         fileSize = [[manager attributesOfItemAtPath:imagePath error:nil] fileSize];
    }
 
    NSString *messageId = nil;
    messageId =  [[IWxChatMgrChat sharedInstance] sendMessageImageToContact:self.contactMemID
                                                                   imagefileURL:imagePath
                                                                           desc:@"图片"
                                                                    isGroupChat:self.isToRoomChat
                                                                       progress:nil];
    
  
    [self sendIMMessageContent:@"图片消息"
                     messageID:messageId
              messaegeFilePath:imagePath
        messageFileServicePath:@""
               messageFileSize:0
                   messageType:kMessageImage
                        durion:0];
   
}
/**
 *  发送小视频－－
 *
 */
- (void)sendRecodVideoFilePath:(NSString *)videoFilePath
{
    
    NSString *messageId = nil;
    
    messageId =  [[IWxChatMgrChat sharedInstance] sendMessageVideoToContact:self.contactMemID
                                                                   videoFileURL:videoFilePath
                                                                       duration:0
                                                                           desc:@"小视频"
                                                                    isGroupChat:self.isToRoomChat
                                                                       progress:self];
        
    
    [self sendIMMessageContent:@"小视频"
                     messageID:messageId
              messaegeFilePath:videoFilePath
        messageFileServicePath:@""
               messageFileSize:0
                   messageType:kMessageVideo
                        durion:0];
}



- (NSString *)getSavePathStr {
    NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    urlStr = [urlStr stringByAppendingPathComponent:kRecordAudioFile];
    return urlStr;
}

- (NSString *)getMP3SavePathStrWithStr:(NSString *)str {
    
    NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    urlStr = [urlStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",str]];
    return urlStr;
}



/**
 *  更新anyChat相关的message
 *
 *  @param notiy
 */
- (void)updateMessageListFromAnyChatNotification:(NSNotification *)notiy
{
    NSDictionary *infoDic = notiy.userInfo;
    NSString *message = infoDic[@"message"];
    NSString *messageID = infoDic[@"messageID"];    
    BOOL isONlyDB = infoDic[@"onlyDB"];
    /**
     *  
     */
    NSString *previousTimeStr = nil;
    ChartCellFrame *previousChartCellFrame = nil;
    if (self.cellFrames.count != 0) {
        previousChartCellFrame = (ChartCellFrame *)[self.cellFrames lastObject];
        previousTimeStr =  previousChartCellFrame.chartMessage.time;
    }
    
    ChartCellFrame *cellFrame=[[ChartCellFrame alloc] init];
    ChartMessage *chartMessage=[[ChartMessage alloc] init];
    chartMessage.messageId = messageID;
    chartMessage.messageType = kMessageTo;//发出的消息
    chartMessage.messageStyle = kMessageText;
    chartMessage.content = message;
    if (isONlyDB) {
        chartMessage.sendIsSuccess = Chat_Send_Success;
    }else{
        chartMessage.sendIsSuccess = Chat_Send_Sending;

    }
    chartMessage.time = [NSString stringFromNSDate:[NSDate  date]];
    chartMessage.showTime = [NSString stringWithPreviousTime:previousTimeStr withLatterTime:[NSString stringFromNSDate:[NSDate  date]]];
    NSInteger row = 0;
    if (!self.cellFrames.count) {
        row = 0;
    }
    else
    {
        row = self.cellFrames.count;
    }
    chartMessage.indexNumber = [NSNumber numberWithInteger:row];
    
    cellFrame.chartMessage = chartMessage;
    
    [self.cellFrames addObject:cellFrame];
    [self.mainTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.cellFrames.count-1  inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self tableViewScrollCurrentIndexPath];

}


/**
 *  发送消息之更新tableView
 *
 *  @param messageContent 文本信息
 *  @param messageID      messageID
 *  @param filepath       文件路径 -或者是文件名称
 *  @param messageType    消息类型
 *  @param duration       文件时长 －－无则默认为0
 */
- (void)sendIMMessageContent:(NSString *)messageContent
                   messageID:(NSString *)messageID
            messaegeFilePath:(NSString *)filepath
      messageFileServicePath:(NSString *)webPath
             messageFileSize:(NSInteger)fileSize
                 messageType:(ChatMessageStyle)messageType
                      durion:(CGFloat)duration
{
    ChartCellFrame *cellFrame  = [[ChartCellFrame alloc] init];
    ChartMessage *chartMessage = [[ChartMessage alloc] init];
    
    NSString *previousTimeStr = nil;
    ChartCellFrame *previousChartCellFrame = nil;
    if (self.cellFrames.count != 0) {
        previousChartCellFrame = (ChartCellFrame *)[self.cellFrames lastObject];
        previousTimeStr =  previousChartCellFrame.chartMessage.time;
    }
    chartMessage.content       = messageContent;
    chartMessage.messageId     = messageID;
    chartMessage.messageType   = kMessageTo;
    chartMessage.messageStyle  = messageType;
   
    chartMessage.fileName      = [filepath lastPathComponent];
    chartMessage.sendIsSuccess = Chat_Send_Sending;
    chartMessage.time          = [NSString stringFromNSDate:[NSDate  date]];
    chartMessage.showTime      = [NSString stringWithPreviousTime:previousTimeStr
                                                   withLatterTime:[NSString stringFromNSDate:[NSDate  date]]];
    chartMessage.duration      = duration;
    if (messageType == kMessageCustom) {
        chartMessage.fileName = filepath;
        chartMessage.fileSize = fileSize;
        chartMessage.messageImageUrl = webPath;
    }
    if (messageType == kMessageImage) {
        chartMessage.messageImageUrl = webPath;
    }
    
    NSInteger row = 0;
    if (!self.cellFrames.count) {
        row = 0;
    }
    else
    {
        row = self.cellFrames.count;
    }
    chartMessage.indexNumber = [NSNumber numberWithInteger:row];
    cellFrame.chartMessage = chartMessage;
    
    [self.cellFrames addObject:cellFrame];
    [self.mainTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.cellFrames.count-1  inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self tableViewScrollCurrentIndexPath];
}

#pragma mark -  KVO
// KVO 改变tableView的高度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // tableView随输入框
    if ([keyPath isEqualToString:@"y"]) {
        self.mainTableView.x = 0;
        self.mainTableView.height = self.textView.y-kNavigationHeight;
        if (self.cellFrames.count > 0) {
            @try {
                [self.mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.cellFrames.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
            @catch (NSException *exception) {
                NSLog(@"-----IM键盘滚动崩溃: %@", exception);
            }
            @finally {
            }
        }
        
    }
}



@end
